<?php

class UserBackController extends BackEndController {

    public function filters() {
        return array(
            'accessControl', // perform access control for CRUD operations
        );
    }

    public function accessRules() {
        return array(
            array(
                'allow',
                'actions' => array('login', 'logout'),
                'users' => array('*'),
            ),
            array(
                'allow',
                'actions' => array('index', 'view', 'create', 'update', 'admin', 'delete', 'log'),
                'users' => array('@'),
                'expression' => 'Yii::app()->user->isAdmin() == "true"',
            ),

            array('deny', // deny all users
                'users' => array('*'),
            ),
        );
    }

    public function actionView($id) {
        $this->render('view', array(
            'model' => $this->loadModel($id),
        ));
    }

    public function actionCreate() {
        $model = new UserBack;

        if (isset($_POST['UserBack'])) {
            $model->attributes = $_POST['UserBack'];
            $pass = $model->password;

            $model->status = $_POST['UserBack']['status'];
            $model->website = $_POST['UserBack']['website'];
            $model->password = md5($model->password);
            $model->confirm_password = $model->password;
            if ($model->save()) {
                $raovat = new UserRaoVatInfo();
                $raovat->first_name = $model->first_name;
                $raovat->last_name = $model->last_name;
                $raovat->ym = '';
                $raovat->phone = '';
                $raovat->address = '';
                $raovat->avata_url = $model->avata_url;
                $raovat->user_id = $model->user_id;
                $raovat->user_name = $model->user_name;
                $raovat->join_time = time();
                $raovat->level = 0;
                $raovat->save();


                $this->redirect(array('index'));
            } else {
                $model->password = $pass;
            }
        }

        $this->render('create', array(
            'model' => $model,
        ));
    }

    public function actionUpdate($id) {
        $model = $this->loadModel($id);
        if (isset($_POST['UserBack'])) {
            $model->attributes = $_POST['UserBack'];
            $model->status = $_POST['UserBack']['status'];
            $model->website = $_POST['UserBack']['website'];
            if ($model->save())
                $this->redirect(array('index'));
        }

        $this->render('update', array(
            'model' => $model,
        ));
    }

    public function actionDelete($id) {
        $this->loadModel($id)->delete();

        // if AJAX request (triggered by deletion via admin grid view), we should not redirect the browser
        if (!isset($_GET['ajax']))
            $this->redirect(isset($_POST['returnUrl']) ? $_POST['returnUrl'] : array('index'));
    }

    public function actionIndex() {
        $model = new UserBack('search');
        $model->unsetAttributes(); // clear any default values
        if (isset($_GET['UserBack']))
            $model->attributes = $_GET['UserBack'];

        $this->render('admin', array(
            'model' => $model,
        ));
    }

    public function loadModel($id) {
        $model = UserBack::model()->findByPk($id);
        if ($model === null)
            throw new CHttpException(404, 'The requested page does not exist.');
        return $model;
    }

    /**
     * Do login using login page.
     * @throws CHttpException
     */
    public function actionLogin() {
        if (!defined('CRYPT_BLOWFISH') || !CRYPT_BLOWFISH)
            throw new CHttpException(500, "This application requires that PHP was compiled with Blowfish support for crypt().");
        if (!Yii::app()->user->isGuest) {
            $this->redirect(Yii::app()->homeUrl);
        }

        $model = new BackendLoginForm();

        // if it is ajax validation request
        if (isset($_POST['ajax']) && $_POST['ajax'] === 'login-form') {
            echo CActiveForm::validate($model);
            Yii::app()->end();
        }

        // collect user input data
        if (isset($_POST['BackendLoginForm'])) {
            $model->attributes = $_POST['BackendLoginForm'];
            $model->password = md5($model->password);

            // validate user input and redirect to the previous page if valid
            if ($model->validate() && $model->login())
                $this->redirect(TreTodayUrl::backendDefaultUrl());
        }
        // display the login form
        $this->render('login', array('model' => $model));
    }

    /**
     * Logs out the current user and redirect to homepage.
     */
    public function actionLogout() {
        Yii::app()->user->logout();
        $this->redirect(TreTodayUrl::backendUrl());
    }

    public function actionLog() {
        $results = array();
        $date = '';
        if (isset($_POST['date'])) {
            $date = trim($_POST['date']);
            $a = UserBack::model()->findAll(array(
                'select' => array('*'),
                'condition' => 'register_date like :addDate',
                'params' => array(':addDate' => $date . "%"),
            ));

            foreach ($a as $i) {
                array_push($results, array('name' => $i->user_name, 'email' => $i->email));
            }
        }

        $this->render('log', array('model' => $results, 'date' => $date));
    }


}
